package com.webserver.controller;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.vo.Article;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ArticleController {
    //保存所有文章信息的目录名字
    private static String userDirTitle = "./userTitles/";

    static {
        //程序加载时判断一下保存所有用户信息的目录是否存在，不存在先自动创建出来
        File uDT = new File(userDirTitle);
        if (!uDT.exists()){
            uDT.mkdirs();
        }
    }
    public void writearticle(HttpRequest request, HttpResponse response){
        System.out.println("处理发表文章。。。");
        String title =  request.getParameter("title");
        String author =  request.getParameter("author");
        String content =  request.getParameter("content");

        if (title==null||author==null||content==null){
            response.setEntity(new File("./webapps/myweb/articleFail.html"));
            return;
        }
        try(
                ObjectOutputStream oos = new ObjectOutputStream(
                        new FileOutputStream(userDirTitle+title+".obj")
                );
                ){
            Article article = new Article(title,author,content);
            oos.writeObject(article);
            response.setEntity(new File("./webapps/myweb/articleSuccess.html"));
        }catch (IOException e){
            e.printStackTrace();
        }
        System.out.println("处理发表文章完毕！");

    }
}
